"use strict";
define(["jquery", "bootstrap", "backend", "table", "form","vue","editable"], function (e, t, a, i, r,Vue) {
    var l = {
        index: function () {


            i.api.init({
                extend: {
                    index_url: "wanlshop/goods/index" + location.search,
                    add_url: "wanlshop/goods/add",
                    edit_url: "wanlshop/goods/edit",
                    del_url: "wanlshop/goods/del",
                    import_url: "wanlshop/goods/import",
                    multi_url: "wanlshop/goods/multi",
                    table: "wanlshop_goods"
                }
            });
            var t = e("#table");
            t.bootstrapTable({
                url: e.fn.bootstrapTable.defaults.extend.index_url,
                pk: "id",
                sortName: "weigh",
                detailView: true,//父子表
                detailFormatter:function(index,row,detail){

                    var html = "<table class=\"table table-striped table-bordered table-hover table-nowrap\">\n" +
                        " 			<thead>\n" +
                        "               <tr>\n" +
                        "                   <th style=\"text-align: center; vertical-align: middle;\">\n" +
                        "                   <div class=\"th-inner \">规格</div>\n" +
                        "                   </th>\n" +
                        "                   <th style=\"text-align: center; vertical-align: middle;\">\n" +
                        "                       <div class=\"th-inner \">供货价</div>\n" +
                        "                   </th>\n" ;
                    for (var g=0;g<Config.groupList.length;g++){
                        html += "                   <th style=\"text-align: center; vertical-align: middle;\">\n" +
                            "                        <div class=\"th-inner \">"+Config.groupList[g].name+"价格</div>\n" +
                            "                   </th>\n";
                    }
                    html+=
                            "                   <th style=\"text-align: center; vertical-align: middle;\">\n" +
                        "                        <div class=\"th-inner \">建议零售价</div>\n" +
                        "                   </th>\n"+

                        "                   <th style=\"text-align: center; vertical-align: middle;\">\n" +
                        "                        <div class=\"th-inner \">重量(Kg)</div>\n" +
                        "                   </th>\n" +
                        "                   <th style=\"text-align: center; vertical-align: middle;\">\n" +
                        "                        <div class=\"th-inner \">库存</div>\n" +
                        "                   </th>\n" +
                        "                   <th style=\"text-align: center; vertical-align: middle;\">\n" +
                        "                        <div class=\"th-inner \">条形码</div>\n" +
                        "                   </th>\n" +
                        "                </tr>\n" +
                        "             </thead>\n" +
                        "          <tbody>\n" ;
                    for(var i=0;i<row.sku.length;i++){
                        html += "<tr>\n" +
                            "<td style=\"text-align: center; vertical-align: middle;\">"+row.sku[i].difference+"</td>\n" +
                            "<td style=\"text-align: center; vertical-align: middle;\"> <input type='number' class='sku_edit_price' onchange='price1(this)'  style='text-align: center;width:50%;' data-group-id='0' data-field='supply_price' data-id='"+row.sku[i].id+"' value='"+row.sku[i].supply_price+"'> </td>\n" ;
                        for (var g=0;g<Config.groupList.length;g++){
                            html += "<td style=\"text-align: center; vertical-align: middle;\">  <input type='number' class='sku_edit_price' onchange='price1(this)' style='text-align: center;width:50%;' data-field='group_price' data-group-id='"+Config.groupList[g].id+"' data-id='"+row.sku[i].id+"' value='"+row.sku[i].group_price[Config.groupList[g].id].price+"'> </td>\n";
                        }
                        html +=
                                "<td style=\"text-align: center; vertical-align: middle;\">  <input type='number' class='sku_edit_price' onchange='price1(this)' style='text-align: center;width:50%;' data-field='price' data-group-id='0' data-id='"+row.sku[i].id+"' value='"+row.sku[i].price+"'></td>\n" +
                            "<td style=\"text-align: center; vertical-align: middle;\"> <input type='number' class='sku_edit_price' onchange='price1(this)' style='text-align: center;width:50%;' data-field='weigh' data-group-id='0' data-id='"+row.sku[i].id+"' value='"+row.sku[i].weigh+"'> </td>\n" +
                            "<td style=\"text-align: center; vertical-align: middle;\"> <input type='number' class='sku_edit_price' onchange='price1(this)' style='text-align: center;width:50%;' data-field='stock' data-group-id='0' data-id='"+row.sku[i].id+"' value='"+row.sku[i].stock+"'> </td>\n" +
                            "<td style=\"text-align: center; vertical-align: middle;\"><input type='text' class='sku_edit_price' onchange='price1(this)' style='text-align: center;width:80%;' data-field='sn' data-group-id='0' data-id='"+row.sku[i].id+"' value='"+row.sku[i].sn+"'> </td>\n" +
                            "</tr>\n" ;
                    }
                    html += " </tbody>\n" +
                        "</table>" ;
                       
                    html += `
                         <script> 
                            function price1(e){
                                var field = $(e).attr("data-field");
                                var id = $(e).attr("data-id");
                                var group_id = $(e).attr("data-group-id");
                                var zhi = $(e).val();
                                var url = "wanlshop/goods/field"
                                console.log(field);
                                console.log(id);
                                console.log(zhi);
                                console.log(group_id);
                                $.post(url, {id: id, field: field,zhi:zhi,group_id:group_id}, function (response) {
                                if (response.code =='1') {
                                    layer.msg('更新成功');
                                } else if (response.code == '0') {
                                    layer.alert(response.msg, {icon: 2})
                                } else {
                                    console.log(response);
                                }
                                 }, 'json')
                            } 
                        </script> 
                    `;

                    detail.html(html);
                },
                columns: [
                    [ {checkbox: !0},
                        {
                            field: "id",
                            title: __("ID"),
                        },

                        {field: "title",
                            title: __("Title")},
                        {
                            field: "image",
                            title: __("Image"),
                            events: i.api.events.image,
                            formatter: i.api.formatter.image
                        },
                        {
                            field: "images",
                            title: __("Images"),
                            events: i.api.events.image,
                            formatter: i.api.formatter.images
                        }, {
                            field: "category.name",
                            title: __("Category.name"),
                            formatter: i.api.formatter.search
                        },
                        /*{
                            field: "supply_price",
                            title: __("供货价"),
                            operate: "BETWEEN",editable:true},*/

                        /*{
                            field: "views", title: __("Views")
                        },
                        {
                            field: "sales", title: __("Sales")},
                        {
                            field: "comment",
                            title: __("Comment")
                        },
                        {
                            field: "praise", title: __("Praise")
                        },
                        {
                            field: "like", title: __("Like")
                        },*/
                        {
                            field: "weigh",
                            title: __("Weigh")
                        },
                        {field: 'exp_date', title: __('过期日期'), operate:'RANGE', addclass:'datetimerange', autocomplete:false,editable:true},
                        /*{
                            field: "createtime",
                            title: __("Createtime"),
                            operate: "RANGE",
                            addclass: "datetimerange",
                            formatter: i.api.formatter.datetime
                        }, {
                            field: "updatetime",
                            title: __("Updatetime"),
                            operate: "RANGE",
                            addclass: "datetimerange",
                            formatter: i.api.formatter.datetime
                        },*/
                        {
                            field: "status",
                            title: __("Status"),
                            searchList: {normal: __("Normal"), hidden: __("Hidden")},
                            table: t,
                            formatter: i.api.formatter.toggle
                        },
                        {
                            field: "operate",
                            title: __("Operate"),
                            table: t,
                            events: i.api.events.operate,
                            formatter: i.api.formatter.operate
                        }]]
            });
            t.on('load-success.bs.table',function(data){
                $(".btn-editone").data("area", ["90%","80%"]);
                $(".btn-add").data("area", ["90%","80%"]);
                $(".btn-edit").data("area", ["90%","80%"]);
            });
            i.api.bindevent(t);

            $(".sku_edit_price").on("change",function () {
                alert(111);
            });

        },
        recyclebin: function () {
            i.api.init({extend: {dragsort_url: ""}});
            var t = e("#table");
            t.bootstrapTable({
                url: "wanlshop/goods/recyclebin" + location.search,
                pk: "id",
                sortName: "id",
                columns: [[{checkbox: !0}, {field: "id", title: __("Id")}, {
                    field: "title",
                    title: __("Title"),
                    align: "left"
                }, {
                    field: "deletetime",
                    title: __("Deletetime"),
                    operate: "RANGE",
                    addclass: "datetimerange",
                    formatter: i.api.formatter.datetime
                }, {
                    field: "operate",
                    width: "130px",
                    title: __("Operate"),
                    table: t,
                    events: i.api.events.operate,
                    buttons: [{
                        name: "Restore",
                        text: __("Restore"),
                        classname: "btn btn-xs btn-info btn-ajax btn-restoreit",
                        icon: "fa fa-rotate-left",
                        url: "wanlshop/goods/restore",
                        refresh: !0
                    }, {
                        name: "Destroy",
                        text: __("Destroy"),
                        classname: "btn btn-xs btn-danger btn-ajax btn-destroyit",
                        icon: "fa fa-times",
                        url: "wanlshop/goods/destroy",
                        refresh: !0
                    }],
                    formatter: i.api.formatter.operate
                }]]
            }), i.api.bindevent(t)
        },
        select: function () {
            i.api.init({extend: {index_url: "wanlshop/goods/select"}});
            var t = [], r = e("#table");
            r.on("check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table", function (a, i) {
                "check" == a.type || "uncheck" == a.type ? i = [i] : t = [], e.each(i, function (e, i) {
                    if (a.type.indexOf("uncheck") > -1) {
                        var r = t.indexOf(i.id);
                        r > -1 && t.splice(r, 1)
                    } else -1 == t.indexOf(i.id) && t.push(i.id)
                })
            }), r.bootstrapTable({
                url: e.fn.bootstrapTable.defaults.extend.index_url,
                sortName: "id",
                showToggle: !1,
                showExport: !1,
                columns: [[{checkbox: !0}, {field: "id", title: __("Id")}, {
                    field: "image",
                    title: __("Image"),
                    events: i.api.events.image,
                    formatter: i.api.formatter.image
                }, {field: "title", title: __("Title")}, {
                    field: "updatetime",
                    title: __("Updatetime"),
                    operate: "RANGE",
                    addclass: "datetimerange",
                    formatter: i.api.formatter.datetime
                }, {
                    field: "operate", title: __("Operate"), events: {
                        "click .btn-chooseone": function (e, t, i, r) {
                            var l = a.api.query("multiple");
                            l = "true" == l, Fast.api.close({url: i.id, multiple: l})
                        }
                    }, formatter: function () {
                        return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __("Choose") + "</a>"
                    }
                }]]
            }), e(document).on("click", ".btn-choose-multi", function () {
                var e = a.api.query("multiple");
                e = "true" == e, Fast.api.close({url: t.join(","), multiple: e})
            }), i.api.bindevent(r)
        },
        add: function() {
            var vm = new Vue({
                el: '#app',
                data() {
                    return {
                        spu: [],
                        spuItem: [],
                        sku: [],
                        batch: 0,
                        categoryId: '',
                        categoryList :Config.channelList,
                        categoryOne: null,
                        categoryTwo: null,
                        categoryThree: null,
                        categoryFour: null,
                        categoryFive: null,
                        attributeData: [],
                        groupList: Config.groupList,
                        packageRules:Config.packageRules,
                        specs:'single',
                    }
                },
                methods: {
                    getCategory(e){
                        if(e == 1){
                            this.categoryTwo = null;
                            this.categoryThree = null;
                            this.categoryFour = null;
                            this.categoryFive = null;
                        }
                        if(this.categoryOne != null){
                            this.categoryId = this.categoryList[this.categoryOne].id;
                        }
                        if(this.categoryTwo != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].id;
                        }
                        if(this.categoryThree != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].id;
                        }
                        if(this.categoryFour != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].childlist[this.categoryFour].id;
                        }
                        if(this.categoryFive != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].childlist[this.categoryFour].childlist[this.categoryFive].id;
                        }
                        // 查询类目属性
                        Fast.api.ajax("wanlshop.goods/attribute?id=" + this.categoryId, (data, ret) =>{
                            this.attributeData = data;
                            //返回false时将不再有右上角的操作成功的提示
                            return false;
                        });
                    },
                    // 添加属性
                    spuAdd(){
                        var str = this.$refs['specs-name'].value || ''
                        str = str.trim();
                        if (!str){
                            Toastr.error("产品属性不能为空");
                            return
                        }
                        // 遍历
                        var arr = str.split(/\s+/);
                        for (var i=0;i<arr.length;i++)
                        {
                            this.spu.push(arr[i])
                        }
                        // 清空表单
                        this.$refs['specs-name'].value = ''
                    },
                    // 删除属性
                    spuRemove(key){
                        Vue.delete(vm.spuItem, key);
                        Vue.delete(vm.spu, key);
                        this.skuCreate();
                    },
                    // 添加规格
                    skuAdd(index) {
                        var str = this.$refs['specs-name-' + index][0].value || ''
                        str = str.trim();
                        if (!str){
                            Toastr.error("产品属性不能为空")
                            return
                        }
                        // 遍历
                        var arr = str.split(/\s+/);
                        for (var i=0;i<arr.length;i++)
                        {
                            if (this.spuItem[index]) {
                                this.spuItem[index].push(arr[i])
                            } else {
                                this.spuItem.push([arr[i]])
                            }
                        }
                        // 清空表单
                        this.$refs['specs-name-' + index][0].value = ""
                        this.skuCreate();
                    },
                    // 删除规格
                    skuRemove(i,key){
                        Vue.delete(vm.spuItem[i], key);
                        this.skuCreate();
                    },
                    // 生成Sku
                    skuCreate() {
                        this.sku = this.skuDesign(this.spuItem)
                    },
                    skuDesign(array) {
                        if (array.length == 0) return []
                        if (array.length < 2) {
                            var res = []
                            array[0].forEach(function(v) {
                                res.push([v])
                            })
                            return res
                        }
                        return [].reduce.call(array, function(col, set) {
                            var res = [];
                            col.forEach(function(c) {
                                set.forEach(function(s) {
                                    var t = [].concat(Array.isArray(c) ? c : [c]);
                                    t.push(s);
                                    res.push(t);
                                })
                            });
                            return res;
                        });
                    },
                    // 是否开启批量
                    skuBatch(){
                        this.batch = this.batch == 0 ? 1 : 0;
                    },

                    onGroupVal(){
                        var group_price = [];
                        $('.wanl-group_price').each(function (i,e) {
                            var price = {
                                group_id:$(this).data('group_id'),
                                price: $(this).val()
                            }
                            group_price[$(this).data('index')] = group_price[$(this).data('index')]||[];
                            group_price[$(this).data('index')].push(price);
                        })
                        group_price.forEach((elem,index) => {
                            var group_price = JSON.stringify(elem);
                            $('.group_price_' + index).val(group_price);
                        })
                    },
                    batchSet(field){
                        console.log('wanl-' + field);
                        $('.wanl-' + field).val($('.batch-' + field).val())
                        this.onGroupVal()
                    }
                }
            })
            window.batchSet = function(field) {
                $('.wanl-' + field).val($('#batch-' + field).val())
            }
            // 完善寄件信息
            $(document).on("click", ".btn-send", function () {
                Backend.api.open('wanlshop/config/index/type/mailing/', __('完善寄件人信息'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 完善退件信息
            $(document).on("click", ".btn-return", function () {
                Backend.api.open('wanlshop/config/index/type/return/', __('完善退货信息'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 申请品牌
            $(document).on("click", ".btn-brand", function () {
                Backend.api.open('wanlshop/brand/add/', __('申请品牌'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 新建运费模板
            $(document).on("click", ".btn-freight", function () {
                Backend.api.open('wanlshop/freight/add', __('新建运费模板'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 新建店铺分类
            $(document).on("click", ".btn-shopsort", function () {
                Backend.api.open('wanlshop/shopsort/add', __('新建店铺分类'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            l.api.bindevent();
        },
        edit: function() {
            l.api.bindevent();
            var vm = new Vue({
                el: '#app',
                data() {
                    return {
                        spu: Config.spu,
                        spuItem: Config.spuItem,
                        sku: Config.sku,
                        skuItem: Config.skuItem,
                        categoryId: Config.categoryId,
                        categoryList :Config.channelList,
                        categoryOne: null,
                        categoryTwo: null,
                        categoryThree: null,
                        categoryFour: null,
                        categoryFive: null,
                        attribute: Config.attribute,
                        attributeData: [],
                        batch: 0,
                        groupList: Config.groupList,
                        packageRules:Config.packageRules,
                        specs:Config.row.specs,
                        goodsSku:Config.goodsSku,
                    }
                },
                mounted() {
                    console.log(this.goodsSku)
                    this.categoryList.forEach((item,index)=>{
                        if (item.id == Config.categoryId ) {
                            this.categoryOne = index;
                        }else{
                            item.childlist.forEach((item1,index1)=>{
                                if (item1.id == Config.categoryId ) {
                                    this.categoryOne = index;
                                    this.categoryTwo = index1;
                                }else{
                                    item1.childlist.forEach((item2,index2)=>{
                                        if (item2.id == Config.categoryId ) {
                                            this.categoryOne = index;
                                            this.categoryTwo = index1;
                                            this.categoryThree = index2;
                                        }else{
                                            item2.childlist.forEach((item3,index3)=>{
                                                if (item3.id == Config.categoryId ) {
                                                    this.categoryOne = index;
                                                    this.categoryTwo = index1;
                                                    this.categoryThree = index2;
                                                    this.categoryFour = index3;
                                                }else{
                                                    item3.childlist.forEach((item4,index4)=>{
                                                        if (item4.id == Config.categoryId ) {
                                                            this.categoryOne = index;
                                                            this.categoryTwo = index1;
                                                            this.categoryThree = index2;
                                                            this.categoryFour = index3;
                                                            this.categoryFive = index4;
                                                        }
                                                    });
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        }
                    });
                    Fast.api.ajax("wanlshop.goods/attribute?id=" + this.categoryId, (data, ret) =>{
                        this.attributeData = data;
                        //返回false时将不再有右上角的操作成功的提示
                        return false;
                    });
                    this.onGroupVal();
                },
                methods: {
                    getCategory(e){
                        if(e == 1){
                            this.categoryTwo = null;
                            this.categoryThree = null;
                            this.categoryFour = null;
                            this.categoryFive = null;
                        }
                        if(this.categoryOne != null){
                            this.categoryId = this.categoryList[this.categoryOne].id;
                        }
                        if(this.categoryTwo != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].id;
                        }
                        if(this.categoryThree != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].id;
                        }
                        if(this.categoryFour != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].childlist[this.categoryFour].id;
                        }
                        if(this.categoryFive != null){
                            this.categoryId = this.categoryList[this.categoryOne].childlist[this.categoryTwo].childlist[this.categoryThree].childlist[this.categoryFour].childlist[this.categoryFive].id;
                        }
                        // 查询类目属性
                        Fast.api.ajax("wanlshop.goods/attribute?id=" + this.categoryId, (data, ret) =>{
                            this.attributeData = data;
                            //返回false时将不再有右上角的操作成功的提示
                            return false;
                        });
                    },
                    // 添加属性
                    spuAdd(){
                        var str = this.$refs['specs-name'].value || ''
                        str = str.trim();
                        if (!str){
                            Toastr.error("产品属性不能为空");
                            return
                        }
                        // 遍历
                        var arr = str.split(/\s+/);
                        for (var i=0;i<arr.length;i++)
                        {
                            this.spu.push(arr[i])
                        }
                        // 清空表单
                        this.$refs['specs-name'].value = ''
                    },
                    // 添加规格
                    skuAdd(index) {
                        var str = this.$refs['specs-name-' + index][0].value || ''
                        str = str.trim();

                        if (!str){
                            Toastr.error("产品属性不能为空")
                            return
                        }
                        // 遍历
                        var arr = str.split(/\s+/);
                        for (var i=0;i<arr.length;i++)
                        {
                            if (this.spuItem[index]) {
                                this.spuItem[index].push(arr[i])
                            } else {
                                this.spuItem.push([arr[i]])
                            }
                        }
                        // 清空表单
                        this.$refs['specs-name-' + index][0].value = ""
                        this.skuCreate();
                    },


                    // 删除属性
                    spuRemove(key){
                        Vue.delete(vm.spuItem, key);
                        Vue.delete(vm.spu, key);
                        this.skuCreate();
                    },
                    // 删除规格
                    skuRemove(i,key){
                        Vue.delete(vm.spuItem[i], key);
                        this.skuCreate();
                    },
                    // 生成Sku
                    skuCreate() {
                        this.sku = this.skuDesign(this.spuItem)
                    },
                    skuDesign(array) {
                        if (array.length == 0) return []
                        if (array.length < 2) {
                            var res = []
                            array[0].forEach(function(v) {
                                res.push([v])
                            })
                            return res
                        }
                        return [].reduce.call(array, function(col, set) {
                            var res = [];
                            col.forEach(function(c) {
                                set.forEach(function(s) {
                                    var t = [].concat(Array.isArray(c) ? c : [c]);
                                    t.push(s);
                                    res.push(t);
                                })
                            });
                            return res;
                        });
                    },
                    // 是否开启批量
                    skuBatch(){
                        this.batch = this.batch == 0 ? 1 : 0;
                    },

                    onGroupVal(){
                        var group_price = [];
                        $('.wanl-group_price').each(function (i,e) {
                            var price = {
                                group_id:$(this).data('group_id'),
                                price: $(this).val()
                            }
                            group_price[$(this).data('index')] = group_price[$(this).data('index')]||[];
                            group_price[$(this).data('index')].push(price);
                        })
                        group_price.forEach((elem,index) => {
                            var group_price = JSON.stringify(elem);
                            $('.group_price_' + index).val(group_price);
                        })
                    },
                    batchSet(field){
                        console.log('wanl-' + field);
                        $('.wanl-' + field).val($('.batch-' + field).val())
                        this.onGroupVal()
                    }
                }
            })
            window.batchSet = function(field) {
                $('.wanl-' + field).val($('#batch-' + field).val())
            }
            // 申请品牌
            $(document).on("click", ".btn-brand", function () {
                Backend.api.open('wanlshop/brand/add/', __('申请品牌'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 新建运费模板
            $(document).on("click", ".btn-freight", function () {
                Backend.api.open('wanlshop/freight/add', __('新建运费模板'), {
                    callback:function(value){
                        console.log(value);
                    }
                });
            });
            // 新建店铺分类
            $(document).on("click", ".btn-shopsort", function () {
                Backend.api.open('wanlshop/shopsort/add', __('新建店铺分类'), {
                    callback:function(value){
                        console.log(value);
                    }
                });

            });

        },

        api: {
            bindevent: function () {
                r.api.bindevent(e("form[role=form]"))
            }
        }
    };


    return l
});



